package com.example.HelloSpace.repository;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import static androidx.core.content.ContentProviderCompat.requireContext;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.HelloSpace.database.AppDatabase;
import com.example.HelloSpace.database.entities.SpaceMissionEntity;
import com.example.HelloSpace.models.ContentModel;
import com.example.HelloSpace.models.MissionInfoModel;
import com.example.HelloSpace.network.WebApiService;
import com.example.HelloSpace.utils.ToastShow;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MissionRepository {
    private WebApiService webApiService;
    private Context context;
    private AppDatabase db;
    private final Executor executor = Executors.newSingleThreadExecutor();
    private MutableLiveData<List<MissionInfoModel>> allMissions = new MutableLiveData<>();
    private MutableLiveData<List<MissionInfoModel>> subscribedMissions = new MutableLiveData<>();
    private MutableLiveData<MissionInfoModel> selectedMission = new MutableLiveData<>();
    private MutableLiveData<ContentModel> contentModelMutableLiveData= new MutableLiveData<>();
    public MissionRepository(WebApiService webApiService, Context context) {
        this.webApiService = webApiService;
        this.context = context;
        db=AppDatabase.getDatabase(context);
//        executor.execute(() -> {
//            db.spaceMissionDao().deleteAll();
//        });
        fetchMissionInfoList();
    }

    //获取任务列表
    private void fetchMissionInfoList() {
        webApiService.getMissionInfoList().enqueue(new Callback<List<MissionInfoModel>>() {
            @Override
            public void onResponse(Call<List<MissionInfoModel>> call, Response<List<MissionInfoModel>> response) {
                if (response.isSuccessful()) {
                    allMissions.setValue(response.body());
                } else {
                    Log.d(TAG, "响应错误");
                    // 处理错误响应...
                }
            }

            @Override
            public void onFailure(Call<List<MissionInfoModel>> call, Throwable t) {
                // 处理失败情况...
                //ToastShow.show(null, "网络错误");
                Log.d(TAG, "网络错误");
            }
        });
    }
    public void refreshMissions() {
        fetchMissionInfoList();
    }

    public LiveData<List<MissionInfoModel>> getAllMissions() {
        return allMissions;
    }

    //通过任务ID获取任务详情
    public LiveData<ContentModel> getMissionDetails(int missionId) {
        webApiService.getMissionDetails(missionId).enqueue(new Callback<ContentModel>() {
            @Override
            public void onResponse(Call<ContentModel> call, Response<ContentModel> response) {
                if (response.isSuccessful()) {
                    contentModelMutableLiveData.setValue(response.body());
                } else {
                    // 处理错误响应...
                }
            }

            @Override
            public void onFailure(Call<ContentModel> call, Throwable t) {
                // 处理失败情况...
            }
        });
        return contentModelMutableLiveData;
    }

    public LiveData<MissionInfoModel> getSelectedMission() {
        return selectedMission;
    }
    public void setSelectedMission(MissionInfoModel missionInfoModel) {
        selectedMission.setValue(missionInfoModel);
    }
    public void saveSubscribedMission(SpaceMissionEntity entity) {
        executor.execute(() -> {
            try {
                db.spaceMissionDao().insert(entity);
            } catch (Exception e) {
                // 处理异常，比如记录日志等
                Log.e("SpaceMissionRepo", "Error inserting mission: " + e.getMessage());
            }
        });
        //ToastShow.show(context, "订阅成功");

    }
    public void cancelSubscribedMission(long id) {
        executor.execute(() -> {
            try {
                db.spaceMissionDao().deleteSpaceMissionById(id);
            } catch (Exception e) {
                // 处理异常，比如记录日志等
                Log.e("SpaceMissionRepo", "Error deleting mission: " + e.getMessage());
            }
        });
        //ToastShow.show(context, "订阅已取消");

    }
    public LiveData<Boolean> isMissionExists(long missionId) {
        MutableLiveData<Boolean> liveData = new MutableLiveData<>();

        executor.execute(() -> {
            Boolean exists = db.spaceMissionDao().isMissionExists(missionId);
            liveData.postValue(exists); // 使用postValue确保在主线程更新
        });

        return liveData;
    }
}
